//群组创建
exports.create = function(req , res){
	//console.log(res);
	//res.send();
	//console.log(res);
	var express = require('express'),
	formidable = require('formidable'),
	async = require('async'),
	md5 = require('md5'),
	fs = require('fs'),
	AVATAR_UPLOAD_FOLDER = '/group/';
	var theTime = parseInt((new Date()).valueOf()/1000);
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	client.connect();
	client.query("use " + myDb.DbName);
	var form = new formidable.IncomingForm();
	form.encoding = 'utf-8';
	form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;
	form.keepExtensions = true;
	//上传限制 3M;
	form.maxFieldsSize = 3 * 1024 * 1024;
	var async = require('async');
		async.waterfall([
			function(callback){
				form.parse(req, function(err, fields, files){
					//console.log(fields['key']);
					if(fields){
						var keycode = fields['key'].replace(' ','+');
						var keycode = aes.decode(keycode , key);
						var keycode = keycode.split('|');
						var hid = fields.hid?fields.hid:"";
						var gType = fields['gType'] ? fields['gType'] : "";
						var groupName = fields['groupName'] ? fields['groupName'] : "";
						var groupNote = fields['groupNote'] ? fields['groupNote'] : "";
						var uid = keycode[2];
						var nickName = keycode[3];
						if(uid){
							if (err)
								res.send(JSON.stringify({code:'3'}));
							if(files.file.size){
								var extName = '';  //后缀名
								switch (files.file.type) {
									case 'image/pjpeg':
									extName = 'jpg';
									break;
									case 'image/jpeg':
									extName = 'jpg';
									break;
									case 'image/gif':
									extName = 'gif';
									break;						
									case 'image/png':
									extName = 'png';
									break;
									case 'image/x-png':
									extName = 'png';
									break;	 
								}
								if(extName.length > 0){
									var avatarName = '' + md5(Math.random()).substr(0,14) + '.' + extName;
									var newPath = form.uploadDir + avatarName;
									//重命名
									fs.renameSync(files.file.path, newPath);
									callback(null,{uid:uid,hid:hid,uName:nickName,gType:gType,groupName:groupName,groupNote:groupNote,path:AVATAR_UPLOAD_FOLDER+avatarName});
								}
								else{
									//文件格式错误;
									res.send(JSON.stringify({code:'2'}));
								}
							}
							else
								res.send(JSON.stringify({code:'3'}));
						}
						else
							res.send(JSON.stringify({code:'3'}));
					}
					else
						res.send(JSON.stringify({code:'3'}));
				});
			},
			function(a1 , callback){
				client.query("INSERT INTO `360_group` (`gid`, `uid`,`hid`, `uName`, `gType`, `groupName`, `groupNote`, `headPath`, `addtime`) VALUES (NULL, '"+a1.uid+"','"+a1.hid+"', '"+a1.uName+"', '"+a1.gType+"', '"+a1.groupName+"', '"+a1.groupNote+"', '"+a1.path+"', "+theTime+"); ",
					function selectCb(err, returnData){
						if(returnData.insertId)
							callback(null,{gid:returnData.insertId,uid:a1.uid});
						else
							res.send(JSON.stringify({code:'3'}));
					}
				)		
			},
			function(b1 , callback){
				client.query("INSERT INTO `360_group_member` (`id`, `gid`, `type`, `uid`, `addtime`,`ViewTime`) VALUES (NULL, '"+b1.gid+"', '1', '"+b1.uid+"', '"+theTime+"','"+theTime+"');",
					function selectCb(err, returnData){
						if(returnData.insertId)
							res.send(JSON.stringify({code:'1'}));
						else
							res.send(JSON.stringify({code:'3'}));
					}
				)
			}],
			function (err, result) {
				
				return;
			}
		)
}


//群信息查看
exports.dataShow = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var gid = req.body.gid;
	var mysql = require('mysql');
	//console.log('SELECT b.`nickName` , a.`uName`, a.`gType`,a.`groupName`,a.`groupNote`,a.`headPath` FROM  `360_group` as a join `360_member` as b where a.`uid` = b.id and a.`gid` = ' + gid + ' limit 1');
	var client = mysql.createConnection(myDb);
	client.connect();
	client.query("use " + myDb.DbName);	
		if(keycode[2] && gid){
			console.log('SELECT `gType`,`uName`,`groupName`,`groupNote`,`headPath` FROM  `360_group` where `gid`='+gid);
			client.query('SELECT `gType`,`uName`,`groupName`,`groupNote`,`headPath` FROM  `360_group` where `gid`='+gid,
				function selectCb(err, data , fields){
					if(data.length)
						res.send(JSON.stringify({code:'1',data:data}));
					else
						res.send(JSON.stringify({code:'2'}));
				}
			)
		}
		else
			res.send(JSON.stringify({code:'3'}));
}




//群组列表
exports.list = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	var async = require('async');
	client.connect();
	client.query("use " + myDb.DbName);
	if(keycode[2]){
		async.waterfall([
			function(callback){
				client.query('SELECT b.gid,b.groupName,b.hid,b.headPath,b.uName FROM  `360_group_member` as a join `360_group` as b where a.gid = b.gid and a.uid = '+keycode[2],
					function selectCb(err, results, fields){
						console.log('SELECT b.gid,b.groupName,b.headPath,b.uName FROM  `360_group_member` as a join `360_group` as b where a.gid = b.gid and a.uid = '+keycode[2]);
						if(results.length)
							res.send(JSON.stringify({code:"1",data:results}));
						else
							res.send(JSON.stringify({code:'1',data:[]}));
					}
				)
			},
			function(a1,callback){
				
			}],
			function (err, result) {
				res.send();
			}
		)
	}
	else
		res.send(JSON.stringify({code:'2'}));
	
}



//群成员列表
exports.memberlist = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var gid = req.body.gid;
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	var async = require('async');
	client.connect();
	client.query("use " + myDb.DbName);
	if(keycode[2]){
		client.query('SELECT a.`gid`,a.`type`,a.`uid`,b.`nickName`,b.`headPath`,b.`signature` FROM  `360_group_member` as a join `360_member` as b where a.gid = '+gid +' and a.uid=b.id',
			function selectCb(err, results, fields){
				var isGroupMember = false;
				if(results.length){
					for(i in results){
						if(results[i].uid == keycode[2]){
							res.send(JSON.stringify({code:"1",data:results,membersum:results.length}));
							isGroupMember = 1;
						}
					}
					if(isGroupMember == false)
						res.send(JSON.stringify({code:'2'}));
				}
				else
					res.send(JSON.stringify({code:'2'}));
			}
		)
	}
	else
		res.send(JSON.stringify({code:'2'}));
}




//群组资料编辑
exports.dataEdit = function(req , res){
	var express = require('express'),
	formidable = require('formidable'),
	async = require('async'),
	md5 = require('md5'),
	fs = require('fs'),
	AVATAR_UPLOAD_FOLDER = '/group/';
	var theTime = parseInt((new Date()).valueOf()/1000);
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	client.connect();
	client.query("use " + myDb.DbName);
	var form = new formidable.IncomingForm();
	form.encoding = 'utf-8';
	form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;
	form.keepExtensions = true;
	//上传限制 3M;
	form.maxFieldsSize = 3 * 1024 * 1024;
	var async = require('async');
		async.waterfall([
			function(callback){
				form.parse(req, function(err, fields, files){
					var keycode = fields['key'].replace(' ','+');
					var keycode = aes.decode(keycode , key);
					var keycode = keycode.split('|');
					var gType = fields['gType'] ? fields['gType'] : "";
					var groupName = fields['groupName'] ? fields['groupName'] : "";
					var groupNote = fields['groupNote'] ? fields['groupNote'] : "";
					var uid = keycode[2];
					var gid = fields['gid'];					
					if(files.file.size){
						if(uid && gid){
							if(files.file.size){
								var extName = '';  //后缀名
								switch (files.file.type) {
									case 'image/pjpeg':
									extName = 'jpg';
									break;
									case 'image/jpeg':
									extName = 'jpg';
									break;
									case 'image/gif':
									extName = 'gif';
									break;						
									case 'image/png':
									extName = 'png';
									break;
									case 'image/x-png':
									extName = 'png';
									break;	 
								}
								if(extName.length > 0){
									var avatarName = '' + md5(Math.random()).substr(0,14) + '.' + extName;
									var newPath = form.uploadDir + avatarName;
									//重命名
									fs.renameSync(files.file.path, newPath);
									callback(null,{gid:gid,uid:uid,gType:gType,groupName:groupName,groupNote:groupNote,path:AVATAR_UPLOAD_FOLDER+avatarName});
								}
								else{
									//文件格式错误;
									res.send(JSON.stringify({code:'2'}));
									return;
								}
							}
							else
								callback(null,{gid:gid,uid:uid,gType:gType,groupName:groupName,groupNote:groupNote});
						}
						else
							res.send(JSON.stringify({code:'3'}));
					}
					else
						callback(null,{gid:gid,uid:uid,gType:gType,groupName:groupName,groupNote:groupNote});
				});
			},
			function(a1 , callback){
				var upPath = a1.path ? ",`headPath` =  '"+a1.path+"'" : "";
				console.log("UPDATE `360_group` SET  `gType` =  '"+a1.gType+"',`groupName` =  '"+a1.groupName+"',`groupNote` =  '"+a1.groupNote+"' "+upPath+" WHERE  `gid` ="+a1.gid+" and `uid` = "+a1.uid+" LIMIT 1 ;");
				client.query("UPDATE `360_group` SET  `gType` =  '"+a1.gType+"',`groupName` =  '"+a1.groupName+"',`groupNote` =  '"+a1.groupNote+"' "+upPath+" WHERE  `gid` ="+a1.gid+" and `uid` = "+a1.uid+" LIMIT 1 ;",
					function selectCb(err, returnData){
						console.log(returnData.affectedRows);
						if(returnData.affectedRows)
							res.send(JSON.stringify({code:'1'}));
						else
							res.send(JSON.stringify({code:'2'}));
					}
				)		
			}],
			function (err, result) {
				return;
			}
		)
}

//申请加入群组
exports.addVerify = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var theTime = parseInt((new Date()).valueOf()/1000);

	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	client.connect();
	client.query("use " + myDb.DbName);
	//if(keycode[2]){
	var gid = req.body.gid;
	var uid = keycode[2];
	var async = require('async');
	var nickName = keycode[3];
		if(uid && gid){
			async.waterfall([
				function(callback){
					client.query('SELECT * FROM  `360_group` where `gid` = ' + gid + ' limit 1',
						function selectCb(err, data , fields){
							if(data.length){
								var gid = "" + data[0].gid;
								var createId = "" + data[0].uid;
								callback(null,{gid:gid,uid:uid,oid:createId,hid:data[0].hid});
							}
							else
								res.send(JSON.stringify({code:'2'}));
						}
					)
				},
				function(a1 , callback){
					client.query('INSERT INTO `360_group_verify` (`id`, `uid`, `oid`, `gid`, `state`, `addtime`) VALUES(NULL, '+a1.uid+', '+a1.oid+', '+a1.gid+', 1,'+theTime+');',
						function selectCb(err, inData , fields){
							/*  跳过入群验证 给出key  */
							if(inData.insertId)
								res.send(JSON.stringify({code:'1',hid:a1.hid,key:aes.encode(theTime+"|"+"13333333333"+"|"+a1.oid+"|"+"/od/jjj.png",key)}));
							else
								res.send(JSON.stringify({code:'2'}));
						}
					)
				}],
				function (err, result) {
						return false;
				}
			)
		}
		else
			res.send(JSON.stringify({code:'2'}));
}



//入群验证
exports.confirmVerify = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var theTime = parseInt((new Date()).valueOf()/1000);
	var uid = keycode[2];
	var type = req.body.type=="1" ? 2 : 3;
	//申请者id
	var oid = req.body.uid;
	var async = require('async');
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	client.connect();
	client.query("use " + myDb.DbName);
	//console.log('SELECT * FROM  `360_group_verify` where `oid` = ' + uid + ' and `uid` = '+ oid +'  and `state` = 1 limit 1');
	if(uid){
		async.waterfall([
			function(callback){
				client.query('SELECT * FROM  `360_group_verify` where `oid` = ' + uid + ' and `uid` = '+ oid +'  and `state` = 1 limit 1',
					function selectCb(err, data , fields){
						if(data.length){
							var vid = ""+data[0]['gid']; 
							callback(null,vid);
						}
						else
							res.send(JSON.stringify({code:'2'}));
					}
				)				
			},
			function(a1 , callback){
				client.query("UPDATE `360_group_verify` SET  `state` = "+type+" WHERE  `gid` ="+a1+" and `state`=1 LIMIT 1",
					function selectCb(err, data , fields){
						if(data.changedRows){
							if(type==2)
								callback(null,a1);
							else
								res.send(JSON.stringify({code:'1'}));
						}
						else
							res.send(JSON.stringify({code:'2'}));
					}
				)				
			},
			function(b1 , callback){
				client.query("INSERT INTO `360_group_member` (`id`, `gid`, `type`, `uid`,`ViewTime`,`addtime`) VALUES(NUll, "+b1+", 2, "+oid+" , "+theTime+" , "+theTime+")",
					function selectCb(err, data , fields){
						if(data.insertId)
							res.send(JSON.stringify({code:'1'}));
						else
							res.send(JSON.stringify({code:'2'}));
					}
				)				
			}],
			function (err, result){
				return false;
			}
		)
	}
	else
		res.send(JSON.stringify({code:'2'}));
}

